package joodle.tools;

import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;

import joodle.domain.Point;

public class TranslationTool extends TransformationTool {
	
	/**
	 * Invoked when the mouse button has been clicked (pressed and released) on a component.
	 * @see TransformationTool#handlePress(Point, boolean)
	 */
	@Override
	public void handlePress(Point p, boolean ctrl) {
		super.handlePress(p, ctrl);
		if(transformedShape != null) {
			firstPoint = transformedShape.getCenter();
		}
	}

	/**
	 * Invoked when a mouse button has been released on a component.
	 * @see TransformationTool#handleRelease(Point, boolean)
	 */
	@Override
	public void handleRelease(Point p, boolean ctrl) {
		super.handleRelease(p, ctrl);
		firstPoint = null;
	}

	/**
	 * Draws intermediate figures as an indicator of TranslationTool
	 * @see Tool#drawInterim(Graphics)
	 */
	@Override
	public void drawInterim(Graphics g) {
		if(transformedShape == null)
			return;
		
		super.drawInterim(g);
		
		Point c = transformedShape.getCenter();
		Graphics2D g2 = (Graphics2D) g.create();
		g2.setStroke(new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND,
				0, new float[] { 2.0f, 2.0f }, 0));
		g2.setColor(INTERIM_COLOR);
		g2.fill(new java.awt.geom.Ellipse2D.Float(c.getX()-2, c.getY()-2, 4, 4));
		g2.fill(new java.awt.geom.Ellipse2D.Float(
				firstPoint.getX()-2, firstPoint.getY()-2, 4, 4));
		
		String st = String.format("%d,%d", Math.round(c.getX() - firstPoint.getX()),
				Math.round(-c.getY() + firstPoint.getY()));
		g2.drawString(st, (firstPoint.getX() + c.getX()) / 2,
				(firstPoint.getY() + c.getY()) / 2);
		g2.draw(new java.awt.geom.Line2D.Float(
				firstPoint.getX(), firstPoint.getY(), c.getX(), c.getY()));
		
		g2.dispose();
	}

	/**
	 * Invoked when the mouse cursor has been moved onto a component.
	 * @see Tool#handleMove(Point, boolean, boolean)
	 */
	@Override
	public void handleMove(Point p, boolean ctrl, boolean lb) {
		if(!lb || currentPoint == null || transformedShape == null)
			return;
		
		float dx = p.getX() - currentPoint.getX();
		float dy = p.getY() - currentPoint.getY();
		
		AffineTransform at = AffineTransform.getTranslateInstance(dx, dy);
		currentTransform.concatenate(at);
		transformedShape.transform(at);
		
		currentPoint = p;
	}
}
